package cn.easybuy.web.pre;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.easybuy.entity.Order;
import cn.easybuy.entity.Product;
import cn.easybuy.entity.User;
import cn.easybuy.entity.User_Address;
import cn.easybuy.service.order.OrderService;
import cn.easybuy.service.order.OrderServiceImpl;
import cn.easybuy.service.order.Order_DetailService;
import cn.easybuy.service.order.Order_DetailServiceImpl;
import cn.easybuy.service.product.CartService;
import cn.easybuy.service.product.CartServiceImpl;
import cn.easybuy.service.product.ProductService;
import cn.easybuy.service.product.ProductServiceImpl;
import cn.easybuy.service.user.UserAddressService;
import cn.easybuy.service.user.UserAddressServiceImpl;
import cn.easybuy.utils.ShoppingCart;
import cn.easybuy.utils.ShoppingCartItem;
import org.apache.log4j.Logger;

public class CartServlet extends HttpServlet {
	Logger log=Logger.getLogger(CartServlet.class);
	int orderId;//订单编号
	ProductService ps = new ProductServiceImpl();
	OrderService os = new OrderServiceImpl();
	/**
	 * Constructor of the object.
	 */
	public CartServlet() {
		super();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
		}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		try {
			String action = request.getParameter("action");
			if(action.equals("add")){
				//新增方法
				out.print(add(request, response));
			}else if(action.equals("f5")){
				//刷新方法
				ref(request, response);
			}else if(action.equals("update")){
				//修改方法
				out.print(modifyCart(request, response));
			}else if(action.equals("setBuyCar")){
				ShoppingCart cart = getCartFromSession(request);
				request.getSession().setAttribute("cart", cart);
				request.getRequestDispatcher("../common/BuyCarItems.jsp").forward(request, response);

			}else if(action.equals("address")){
				//获取用户地址
				String id = request.getParameter("id");
				ShoppingCart cart = getCartFromSession(request);
				request.getSession().setAttribute("cart", cart);
				UserAddressService us = new UserAddressServiceImpl();
				List<User_Address>list = us.userAddress(id);
				request.setAttribute("addressList", list);
				request.getRequestDispatcher("BuyCar_Two.jsp").forward(request, response);
			}else if(action.equals("submit")){
				//获得当前登录的用户
				User user=(User)session.getAttribute("LoginUser");
				//提交订单
				//首先判断是否需要新增地址
				String addressId=request.getParameter("addressId");//下单地址名称 为-1代表新增地址
				if(addressId.equals("-1")){
					String address=request.getParameter("newAddress");
					String remark=request.getParameter("newRemark");
					//获取新增影响的行数
					int i = new UserAddressServiceImpl().addAddress(Integer.toString(user.getId()), address, remark);
					if(i>0){
						System.out.println("新增地址成功");
						//修改地址标识
						addressId=address;
					}else{
						System.out.println("新增地址失败");
					}
				}
				//创建一个新的订单对象
				Order o = new Order();
				o.setUserId(user.getId());
				o.setLoginName(user.getLoginName());
				o.setUserAddress(addressId);
				ShoppingCart cart=(ShoppingCart)session.getAttribute("cart"); //获取购物车
				o.setCost(cart.getSum());
				orderId = os.addOrder(o);
				if(orderId>0){
					System.out.println("订单生成成功");
					List<ShoppingCartItem> items=cart.getItems();
					Order_DetailService ods=new Order_DetailServiceImpl();
					int result=ods.addOrderDetail(orderId,items);
					if(result>0){
						//清空购物车
						session.removeAttribute("cart");
						out.print("订单详情已提交");
					}else{
						out.print("订单详情提交失败");
					}
				}else{
					System.out.println("订单生成失败");
				}
			}else if (action.equals("Buy_Three")){
				Order order = os.selOrder(orderId);
				request.setAttribute("order",order);
				request.getRequestDispatcher("BuyCar_Three.jsp").forward(request,response);
			}else{
				request.getRequestDispatcher("BuyCar.jsp").forward(request,response);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//新增方法
	public String add(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		//返回结果值
		String result="";
		//获取商品id  与    购买数量
		String id = request.getParameter("entityId");
		String quantityStr = request.getParameter("quantity");
		//默认购买数量为1
		Integer quantity = 1;
		//如果quantity参数不等于空 则购买数量为quantityStr
		if(quantityStr!=null){
			quantity=Integer.parseInt(quantityStr);
		}
		//查询指定的商品
		Product product = ps.findProductById(id);
		//判断商品数量是否充足，如果购买数量大于商品库存 则提示商品数量不足
		if(quantity>product.getStock()){
			return "商品数量不足";
		}
		//从Session中获取购物车
		ShoppingCart cart = getCartFromSession(request);
		//使用result接收addItem方法的返回值
		result = cart.addItem(product, quantity);
		if(result.equals("成功")){
			//调用求和方法，计算总价格
			cart.getTotal();
		}
		return result;
	}
	//获取购物车 从Session  如果购物车为空 则new一个 否则直接获取
	private ShoppingCart getCartFromSession(HttpServletRequest request)
			throws Exception {
		//创建session获取购物车对象
		HttpSession session = request.getSession();
		ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
		//当购物车为未赋值的时候给session中购物车赋值为空对象
		if (cart ==null) {
			cart = new ShoppingCart();
			session.setAttribute("cart", cart);
		}
		//返回购物车对象
		return cart;
	}
	//刷新
	private void ref(HttpServletRequest request,HttpServletResponse response)throws Exception{
		HttpSession session = request.getSession();
		ShoppingCart cart = this.getCartFromSession(request);
		CartService cs = new CartServiceImpl();
		cart = cs.calculate(cart);
		request.getRequestDispatcher("../common/top.jsp").forward(request, response);
	}
	//修改 数量传0代表删除
	public String modifyCart(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		String result="";
		HttpSession session=request.getSession();
		String id=request.getParameter("entityId");
		String quantityStr=request.getParameter("quantity");
		if(id==null||quantityStr==null){
			return "参数不能为空";
		}
		Integer quantity=Integer.parseInt(quantityStr);
		ShoppingCart cart=getCartFromSession(request);
		Product product=ps.findProductById(id);
		if(quantity>product.getStock()){
			return "商品数量不足";
		}
		CartService cs = new CartServiceImpl();
		cart=cs.modifyShoppingCart(Integer.parseInt(id), quantityStr, cart);
		session.setAttribute("cart", cart);
		return "成功";	 
	}
}
